package com.gome.ai.aiparter.ws;

import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

import com.gome.ai.aiparter.SpringContextUtil;
import com.gome.ai.aiparter.ws.cache.AIRecordAbleConnection;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

@Slf4j
@Component
@ServerEndpoint("/ws/{token}")  // 接口路径 ws://localhost:11720/ws/9f135773-1274-40a4-a863-1ca7fcd50943;
public class WebSocketServer {
    private static ConcurrentHashMap<Session,Object> sessionPool = new ConcurrentHashMap<>();

    private Session session;
    private String token;
    private WSConnection role;

    @OnOpen
    public void onOpen(Session session,@PathParam(value = "token") String token) {
        log.info("open token = {}",token);
        this.session = session;
        this.token = token;
        sessionPool.put(session,token);

        if (SpringContextUtil.getBean(AIConfig.class).getToken().contains(token)) {
            AIConnection role = new AIRecordAbleConnection(this);
            log.debug("创建AI连接");
            this.role = role;
        }else {
            role = new UserConnection(this);
            log.debug("创建User连接");
        }

        log.info("session pool size = {}",sessionPool.size());
    }

    @OnMessage
    public void onMessage(String message) {
        log.debug("on message: {}",message);
        role.onMessage(message);
    }

    @OnError
    public void onError(Throwable error) {
        log.error("token = {}",token,error);
    }

    @OnClose
    public void onClose(Session session) {
        role.onClose();

        log.info("close token = {}",token);
        sessionPool.remove(session);
        log.info("session pool size = {}",sessionPool.size());
    }

    public Session getSession() {
        return session;
    }

    public String getToken() {
        return token;
    }

    public WSConnection getRole() {
        return role;
    }

    public void send(String message){
        log.info("send message:{}",message);
        try {
            session.getBasicRemote().sendText(message);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
